home *** CD-ROM | disk | FTP | other *** search
/ Windows Expert / Windows Expert.iso / windownt / awksrc.zip / GAWK-D~1.14 / GAWK~4.INF (.txt) < prev    next >
GNU Info File  |  1993-10-03  |  50KB  |  916 lines

  1. This is Info file gawk.info, produced by Makeinfo-1.47 from the input
  2. file gawk.texi.
  3.    This file documents `awk', a program that you can use to select
  4. particular records in a file and perform operations upon them.
  5.    This is Edition 0.14 of `The GAWK Manual',
  6. for the 2.14 version of the GNU implementation
  7. of AWK.
  8.    Copyright (C) 1989, 1991, 1992 Free Software Foundation, Inc.
  9.    Permission is granted to make and distribute verbatim copies of this
  10. manual provided the copyright notice and this permission notice are
  11. preserved on all copies.
  12.    Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided that
  14. the entire resulting derived work is distributed under the terms of a
  15. permission notice identical to this one.
  16.    Permission is granted to copy and distribute translations of this
  17. manual into another language, under the above conditions for modified
  18. versions, except that this permission notice may be stated in a
  19. translation approved by the Foundation.
  20. File: gawk.info,  Node: Output Separators,  Next: OFMT,  Prev: Print Examples,  Up: Printing
  21. Output Separators
  22. =================
  23.    As mentioned previously, a `print' statement contains a list of
  24. items, separated by commas.  In the output, the items are normally
  25. separated by single spaces.  But they do not have to be spaces; a
  26. single space is only the default.  You can specify any string of
  27. characters to use as the "output field separator" by setting the
  28. built-in variable `OFS'.  The initial value of this variable is the
  29. string `" "', that is, just a single space.
  30.    The output from an entire `print' statement is called an "output
  31. record".  Each `print' statement outputs one output record and then
  32. outputs a string called the "output record separator". The built-in
  33. variable `ORS' specifies this string.  The initial value of the
  34. variable is the string `"\n"' containing a newline character; thus,
  35. normally each `print' statement makes a separate line.
  36.    You can change how output fields and records are separated by
  37. assigning new values to the variables `OFS' and/or `ORS'.  The usual
  38. place to do this is in the `BEGIN' rule (*note `BEGIN' and `END'
  39. Special Patterns: BEGIN/END.), so that it happens before any input is
  40. processed.  You may also do this with assignments on the command line,
  41. before the names of your input files.
  42.    The following example prints the first and second fields of each
  43. input record separated by a semicolon, with a blank line added after
  44. each line:
  45.      awk 'BEGIN { OFS = ";"; ORS = "\n\n" }
  46.                 { print $1, $2 }'  BBS-list
  47.    If the value of `ORS' does not contain a newline, all your output
  48. will be run together on a single line, unless you output newlines some
  49. other way.
  50. File: gawk.info,  Node: OFMT,  Next: Printf,  Prev: Output Separators,  Up: Printing
  51. Controlling Numeric Output with `print'
  52. =======================================
  53.    When you use the `print' statement to print numeric values, `awk'
  54. internally converts the number to a string of characters, and prints
  55. that string.  `awk' uses the `sprintf' function to do this conversion. 
  56. For now, it suffices to say that the `sprintf' function accepts a
  57. "format specification" that tells it how to format numbers (or
  58. strings), and that there are a number of different ways that numbers
  59. can be formatted.  The different format specifications are discussed
  60. more fully in *Note Using `printf' Statements for Fancier Printing:
  61. Printf.
  62.    The built-in variable `OFMT' contains the default format
  63. specification that `print' uses with `sprintf' when it wants to convert
  64. a number to a string for printing.  By supplying different format
  65. specifications as the value of `OFMT', you can change how `print' will
  66. print your numbers.  As a brief example:
  67.      awk 'BEGIN { OFMT = "%d"  # print numbers as integers
  68.                   print 17.23 }'
  69. will print `17'.
  70. File: gawk.info,  Node: Printf,  Next: Redirection,  Prev: OFMT,  Up: Printing
  71. Using `printf' Statements for Fancier Printing
  72. ==============================================
  73.    If you want more precise control over the output format than `print'
  74. gives you, use `printf'.  With `printf' you can specify the width to
  75. use for each item, and you can specify various stylistic choices for
  76. numbers (such as what radix to use, whether to print an exponent,
  77. whether to print a sign, and how many digits to print after the decimal
  78. point).  You do this by specifying a string, called the "format
  79. string", which controls how and where to print the other arguments.
  80. * Menu:
  81. * Basic Printf::                Syntax of the `printf' statement.
  82. * Control Letters::             Format-control letters.
  83. * Format Modifiers::            Format-specification modifiers.
  84. * Printf Examples::             Several examples.
  85. File: gawk.info,  Node: Basic Printf,  Next: Control Letters,  Prev: Printf,  Up: Printf
  86. Introduction to the `printf' Statement
  87. --------------------------------------
  88.    The `printf' statement looks like this:
  89.      printf FORMAT, ITEM1, ITEM2, ...
  90. The entire list of items may optionally be enclosed in parentheses.  The
  91. parentheses are necessary if any of the item expressions uses a
  92. relational operator; otherwise it could be confused with a redirection
  93. (*note Redirecting Output of `print' and `printf': Redirection.). The
  94. relational operators are `==', `!=', `<', `>', `>=', `<=', `~' and `!~'
  95. (*note Comparison Expressions: Comparison Ops.).
  96.    The difference between `printf' and `print' is the argument FORMAT. 
  97. This is an expression whose value is taken as a string; it specifies
  98. how to output each of the other arguments.  It is called the "format
  99. string".
  100.    The format string is the same as in the ANSI C library function
  101. `printf'.  Most of FORMAT is text to be output verbatim. Scattered
  102. among this text are "format specifiers", one per item. Each format
  103. specifier says to output the next item at that place in the format.
  104.    The `printf' statement does not automatically append a newline to its
  105. output.  It outputs only what the format specifies.  So if you want a
  106. newline, you must include one in the format.  The output separator
  107. variables `OFS' and `ORS' have no effect on `printf' statements.
  108. File: gawk.info,  Node: Control Letters,  Next: Format Modifiers,  Prev: Basic Printf,  Up: Printf
  109. Format-Control Letters
  110. ----------------------
  111.    A format specifier starts with the character `%' and ends with a
  112. "format-control letter"; it tells the `printf' statement how to output
  113. one item.  (If you actually want to output a `%', write `%%'.)  The
  114. format-control letter specifies what kind of value to print.  The rest
  115. of the format specifier is made up of optional "modifiers" which are
  116. parameters such as the field width to use.
  117.    Here is a list of the format-control letters:
  118.      This prints a number as an ASCII character.  Thus, `printf "%c",
  119.      65' outputs the letter `A'.  The output for a string value is the
  120.      first character of the string.
  121.      This prints a decimal integer.
  122.      This also prints a decimal integer.
  123.      This prints a number in scientific (exponential) notation. For
  124.      example,
  125.           printf "%4.3e", 1950
  126.      prints `1.950e+03', with a total of four significant figures of
  127.      which three follow the decimal point.  The `4.3' are "modifiers",
  128.      discussed below.
  129.      This prints a number in floating point notation.
  130.      This prints a number in either scientific notation or floating
  131.      point notation, whichever uses fewer characters.
  132.      This prints an unsigned octal integer.
  133.      This prints a string.
  134.      This prints an unsigned hexadecimal integer.
  135.      This prints an unsigned hexadecimal integer.  However, for the
  136.      values 10 through 15, it uses the letters `A' through `F' instead
  137.      of `a' through `f'.
  138.      This isn't really a format-control letter, but it does have a
  139.      meaning when used after a `%': the sequence `%%' outputs one `%'. 
  140.      It does not consume an argument.
  141. File: gawk.info,  Node: Format Modifiers,  Next: Printf Examples,  Prev: Control Letters,  Up: Printf
  142. Modifiers for `printf' Formats
  143. ------------------------------
  144.    A format specification can also include "modifiers" that can control
  145. how much of the item's value is printed and how much space it gets.  The
  146. modifiers come between the `%' and the format-control letter.  Here are
  147. the possible modifiers, in the order in which they may appear:
  148.      The minus sign, used before the width modifier, says to
  149.      left-justify the argument within its specified width.  Normally
  150.      the argument is printed right-justified in the specified width. 
  151.      Thus,
  152.           printf "%-4s", "foo"
  153.      prints `foo '.
  154. `WIDTH'
  155.      This is a number representing the desired width of a field. 
  156.      Inserting any number between the `%' sign and the format control
  157.      character forces the field to be expanded to this width.  The
  158.      default way to do this is to pad with spaces on the left.  For
  159.      example,
  160.           printf "%4s", "foo"
  161.      prints ` foo'.
  162.      The value of WIDTH is a minimum width, not a maximum.  If the item
  163.      value requires more than WIDTH characters, it can be as wide as
  164.      necessary.  Thus,
  165.           printf "%4s", "foobar"
  166.      prints `foobar'.
  167.      Preceding the WIDTH with a minus sign causes the output to be
  168.      padded with spaces on the right, instead of on the left.
  169. `.PREC'
  170.      This is a number that specifies the precision to use when printing.
  171.      This specifies the number of digits you want printed to the right
  172.      of the decimal point.  For a string, it specifies the maximum
  173.      number of characters from the string that should be printed.
  174.    The C library `printf''s dynamic WIDTH and PREC capability (for
  175. example, `"%*.*s"') is supported.  Instead of supplying explicit WIDTH
  176. and/or PREC values in the format string, you pass them in the argument
  177. list.  For example:
  178.      w = 5
  179.      p = 3
  180.      s = "abcdefg"
  181.      printf "<%*.*s>\n", w, p, s
  182. is exactly equivalent to
  183.      s = "abcdefg"
  184.      printf "<%5.3s>\n", s
  185. Both programs output `<**abc>'.  (We have used the bullet symbol "*" to
  186. represent a space, to clearly show you that there are two spaces in the
  187. output.)
  188.    Earlier versions of `awk' did not support this capability.  You may
  189. simulate it by using concatenation to build up the format string, like
  190.      w = 5
  191.      p = 3
  192.      s = "abcdefg"
  193.      printf "<%" w "." p "s>\n", s
  194. This is not particularly easy to read, however.
  195. File: gawk.info,  Node: Printf Examples,  Prev: Format Modifiers,  Up: Printf
  196. Examples of Using `printf'
  197. --------------------------
  198.    Here is how to use `printf' to make an aligned table:
  199.      awk '{ printf "%-10s %s\n", $1, $2 }' BBS-list
  200. prints the names of bulletin boards (`$1') of the file `BBS-list' as a
  201. string of 10 characters, left justified.  It also prints the phone
  202. numbers (`$2') afterward on the line.  This produces an aligned
  203. two-column table of names and phone numbers:
  204.      aardvark   555-5553
  205.      alpo-net   555-3412
  206.      barfly     555-7685
  207.      bites      555-1675
  208.      camelot    555-0542
  209.      core       555-2912
  210.      fooey      555-1234
  211.      foot       555-6699
  212.      macfoo     555-6480
  213.      sdace      555-3430
  214.      sabafoo    555-2127
  215.    Did you notice that we did not specify that the phone numbers be
  216. printed as numbers?  They had to be printed as strings because the
  217. numbers are separated by a dash.  This dash would be interpreted as a
  218. minus sign if we had tried to print the phone numbers as numbers.  This
  219. would have led to some pretty confusing results.
  220.    We did not specify a width for the phone numbers because they are the
  221. last things on their lines.  We don't need to put spaces after them.
  222.    We could make our table look even nicer by adding headings to the
  223. tops of the columns.  To do this, use the `BEGIN' pattern (*note
  224. `BEGIN' and `END' Special Patterns: BEGIN/END.) to force the header to
  225. be printed only once, at the beginning of the `awk' program:
  226.      awk 'BEGIN { print "Name      Number"
  227.                   print "----      ------" }
  228.           { printf "%-10s %s\n", $1, $2 }' BBS-list
  229.    Did you notice that we mixed `print' and `printf' statements in the
  230. above example?  We could have used just `printf' statements to get the
  231. same results:
  232.      awk 'BEGIN { printf "%-10s %s\n", "Name", "Number"
  233.                   printf "%-10s %s\n", "----", "------" }
  234.           { printf "%-10s %s\n", $1, $2 }' BBS-list
  235. By outputting each column heading with the same format specification
  236. used for the elements of the column, we have made sure that the headings
  237. are aligned just like the columns.
  238.    The fact that the same format specification is used three times can
  239. be emphasized by storing it in a variable, like this:
  240.      awk 'BEGIN { format = "%-10s %s\n"
  241.                   printf format, "Name", "Number"
  242.                   printf format, "----", "------" }
  243.           { printf format, $1, $2 }' BBS-list
  244.    See if you can use the `printf' statement to line up the headings and
  245. table data for our `inventory-shipped' example covered earlier in the
  246. section on the `print' statement (*note The `print' Statement: Print.).
  247. File: gawk.info,  Node: Redirection,  Next: Special Files,  Prev: Printf,  Up: Printing
  248. Redirecting Output of `print' and `printf'
  249. ==========================================
  250.    So far we have been dealing only with output that prints to the
  251. standard output, usually your terminal.  Both `print' and `printf' can
  252. also send their output to other places. This is called "redirection".
  253.    A redirection appears after the `print' or `printf' statement.
  254. Redirections in `awk' are written just like redirections in shell
  255. commands, except that they are written inside the `awk' program.
  256. * Menu:
  257. * File/Pipe Redirection::       Redirecting Output to Files and Pipes.
  258. * Close Output::                How to close output files and pipes.
  259. File: gawk.info,  Node: File/Pipe Redirection,  Next: Close Output,  Prev: Redirection,  Up: Redirection
  260. Redirecting Output to Files and Pipes
  261. -------------------------------------
  262.    Here are the three forms of output redirection.  They are all shown
  263. for the `print' statement, but they work identically for `printf' also.
  264. `print ITEMS > OUTPUT-FILE'
  265.      This type of redirection prints the items onto the output file
  266.      OUTPUT-FILE.  The file name OUTPUT-FILE can be any expression. 
  267.      Its value is changed to a string and then used as a file name
  268.      (*note Expressions as Action Statements: Expressions.).
  269.      When this type of redirection is used, the OUTPUT-FILE is erased
  270.      before the first output is written to it.  Subsequent writes do not
  271.      erase OUTPUT-FILE, but append to it.  If OUTPUT-FILE does not
  272.      exist, then it is created.
  273.      For example, here is how one `awk' program can write a list of BBS
  274.      names to a file `name-list' and a list of phone numbers to a file
  275.      `phone-list'.  Each output file contains one name or number per
  276.      line.
  277.           awk '{ print $2 > "phone-list"
  278.                  print $1 > "name-list" }' BBS-list
  279. `print ITEMS >> OUTPUT-FILE'
  280.      This type of redirection prints the items onto the output file
  281.      OUTPUT-FILE.  The difference between this and the single-`>'
  282.      redirection is that the old contents (if any) of OUTPUT-FILE are
  283.      not erased.  Instead, the `awk' output is appended to the file.
  284. `print ITEMS | COMMAND'
  285.      It is also possible to send output through a "pipe" instead of
  286.      into a file.   This type of redirection opens a pipe to COMMAND
  287.      and writes the values of ITEMS through this pipe, to another
  288.      process created to execute COMMAND.
  289.      The redirection argument COMMAND is actually an `awk' expression. 
  290.      Its value is converted to a string, whose contents give the shell
  291.      command to be run.
  292.      For example, this produces two files, one unsorted list of BBS
  293.      names and one list sorted in reverse alphabetical order:
  294.           awk '{ print $1 > "names.unsorted"
  295.                  print $1 | "sort -r > names.sorted" }' BBS-list
  296.      Here the unsorted list is written with an ordinary redirection
  297.      while the sorted list is written by piping through the `sort'
  298.      utility.
  299.      Here is an example that uses redirection to mail a message to a
  300.      mailing list `bug-system'.  This might be useful when trouble is
  301.      encountered in an `awk' script run periodically for system
  302.      maintenance.
  303.           report = "mail bug-system"
  304.           print "Awk script failed:", $0 | report
  305.           print "at record number", FNR, "of", FILENAME  | report
  306.           close(report)
  307.      We call the `close' function here because it's a good idea to close
  308.      the pipe as soon as all the intended output has been sent to it.
  309.      *Note Closing Output Files and Pipes: Close Output, for more
  310.      information on this.  This example also illustrates the use of a
  311.      variable to represent a FILE or COMMAND: it is not necessary to
  312.      always use a string constant.  Using a variable is generally a
  313.      good idea, since `awk' requires you to spell the string value
  314.      identically every time.
  315.    Redirecting output using `>', `>>', or `|' asks the system to open a
  316. file or pipe only if the particular FILE or COMMAND you've specified
  317. has not already been written to by your program, or if it has been
  318. closed since it was last written to.
  319. File: gawk.info,  Node: Close Output,  Prev: File/Pipe Redirection,  Up: Redirection
  320. Closing Output Files and Pipes
  321. ------------------------------
  322.    When a file or pipe is opened, the file name or command associated
  323. with it is remembered by `awk' and subsequent writes to the same file or
  324. command are appended to the previous writes.  The file or pipe stays
  325. open until `awk' exits.  This is usually convenient.
  326.    Sometimes there is a reason to close an output file or pipe earlier
  327. than that.  To do this, use the `close' function, as follows:
  328.      close(FILENAME)
  329.      close(COMMAND)
  330.    The argument FILENAME or COMMAND can be any expression. Its value
  331. must exactly equal the string used to open the file or pipe to begin
  332. with--for example, if you open a pipe with this:
  333.      print $1 | "sort -r > names.sorted"
  334. then you must close it with this:
  335.      close("sort -r > names.sorted")
  336.    Here are some reasons why you might need to close an output file:
  337.    * To write a file and read it back later on in the same `awk'
  338.      program.  Close the file when you are finished writing it; then
  339.      you can start reading it with `getline' (*note Explicit Input with
  340.      `getline': Getline.).
  341.    * To write numerous files, successively, in the same `awk' program. 
  342.      If you don't close the files, eventually you may exceed a system
  343.      limit on the number of open files in one process.  So close each
  344.      one when you are finished writing it.
  345.    * To make a command finish.  When you redirect output through a pipe,
  346.      the command reading the pipe normally continues to try to read
  347.      input as long as the pipe is open.  Often this means the command
  348.      cannot really do its work until the pipe is closed.  For example,
  349.      if you redirect output to the `mail' program, the message is not
  350.      actually sent until the pipe is closed.
  351.    * To run the same program a second time, with the same arguments.
  352.      This is not the same thing as giving more input to the first run!
  353.      For example, suppose you pipe output to the `mail' program.  If you
  354.      output several lines redirected to this pipe without closing it,
  355.      they make a single message of several lines.  By contrast, if you
  356.      close the pipe after each line of output, then each line makes a
  357.      separate message.
  358. File: gawk.info,  Node: Special Files,  Prev: Redirection,  Up: Printing
  359. Standard I/O Streams
  360. ====================
  361.    Running programs conventionally have three input and output streams
  362. already available to them for reading and writing.  These are known as
  363. the "standard input", "standard output", and "standard error output". 
  364. These streams are, by default, terminal input and output, but they are
  365. often redirected with the shell, via the `<', `<<', `>', `>>', `>&' and
  366. `|' operators.  Standard error is used only for writing error messages;
  367. the reason we have two separate streams, standard output and standard
  368. error, is so that they can be redirected separately.
  369.    In other implementations of `awk', the only way to write an error
  370. message to standard error in an `awk' program is as follows:
  371.      print "Serious error detected!\n" | "cat 1>&2"
  372. This works by opening a pipeline to a shell command which can access the
  373. standard error stream which it inherits from the `awk' process. This is
  374. far from elegant, and is also inefficient, since it requires a separate
  375. process.  So people writing `awk' programs have often neglected to do
  376. this.  Instead, they have sent the error messages to the terminal, like
  377. this:
  378.      NF != 4 {
  379.         printf("line %d skipped: doesn't have 4 fields\n", FNR) > "/dev/tty"
  380.      }
  381. This has the same effect most of the time, but not always: although the
  382. standard error stream is usually the terminal, it can be redirected, and
  383. when that happens, writing to the terminal is not correct.  In fact, if
  384. `awk' is run from a background job, it may not have a terminal at all.
  385. Then opening `/dev/tty' will fail.
  386.    `gawk' provides special file names for accessing the three standard
  387. streams.  When you redirect input or output in `gawk', if the file name
  388. matches one of these special names, then `gawk' directly uses the
  389. stream it stands for.
  390. `/dev/stdin'
  391.      The standard input (file descriptor 0).
  392. `/dev/stdout'
  393.      The standard output (file descriptor 1).
  394. `/dev/stderr'
  395.      The standard error output (file descriptor 2).
  396. `/dev/fd/N'
  397.      The file associated with file descriptor N.  Such a file must have
  398.      been opened by the program initiating the `awk' execution
  399.      (typically the shell).  Unless you take special pains, only
  400.      descriptors 0, 1 and 2 are available.
  401.    The file names `/dev/stdin', `/dev/stdout', and `/dev/stderr' are
  402. aliases for `/dev/fd/0', `/dev/fd/1', and `/dev/fd/2', respectively,
  403. but they are more self-explanatory.
  404.    The proper way to write an error message in a `gawk' program is to
  405. use `/dev/stderr', like this:
  406.      NF != 4 {
  407.        printf("line %d skipped: doesn't have 4 fields\n", FNR) > "/dev/stderr"
  408.      }
  409.    Recognition of these special file names is disabled if `gawk' is in
  410. compatibility mode (*note Invoking `awk': Command Line.).
  411.      *Caution*:  Unless your system actually has a `/dev/fd' directory,
  412.      the interpretation of these file names is done by `gawk' itself.
  413.      For example, using `/dev/fd/4' for output will actually write on
  414.      file descriptor 4, and not on a new file descriptor that was
  415.      `dup''ed from file descriptor 4.  Most of the time this does not
  416.      matter; however, it is important to *not* close any of the files
  417.      related to file descriptors 0, 1, and 2.  If you do close one of
  418.      these files, unpredictable behavior will result.
  419. File: gawk.info,  Node: One-liners,  Next: Patterns,  Prev: Printing,  Up: Top
  420. Useful "One-liners"
  421. *******************
  422.    Useful `awk' programs are often short, just a line or two.  Here is a
  423. collection of useful, short programs to get you started.  Some of these
  424. programs contain constructs that haven't been covered yet.  The
  425. description of the program will give you a good idea of what is going
  426. on, but please read the rest of the manual to become an `awk' expert!
  427.    Since you are reading this in Info, each line of the example code is
  428. enclosed in quotes, to represent text that you would type literally.
  429. The examples themselves represent shell commands that use single quotes
  430. to keep the shell from interpreting the contents of the program. When
  431. reading the examples, focus on the text between the open and close
  432. quotes.
  433. `awk '{ if (NF > max) max = NF }'
  434. `     END { print max }''
  435.      This program prints the maximum number of fields on any input line.
  436. `awk 'length($0) > 80''
  437.      This program prints every line longer than 80 characters.  The sole
  438.      rule has a relational expression as its pattern, and has no action
  439.      (so the default action, printing the record, is used).
  440. `awk 'NF > 0''
  441.      This program prints every line that has at least one field.  This
  442.      is an easy way to delete blank lines from a file (or rather, to
  443.      create a new file similar to the old file but from which the blank
  444.      lines have been deleted).
  445. `awk '{ if (NF > 0) print }''
  446.      This program also prints every line that has at least one field. 
  447.      Here we allow the rule to match every line, then decide in the
  448.      action whether to print.
  449. `awk 'BEGIN { for (i = 1; i <= 7; i++)'
  450. `               print int(101 * rand()) }''
  451.      This program prints 7 random numbers from 0 to 100, inclusive.
  452. `ls -l FILES | awk '{ x += $4 } ; END { print "total bytes: " x }''
  453.      This program prints the total number of bytes used by FILES.
  454. `expand FILE | awk '{ if (x < length()) x = length() }'
  455. `                  END { print "maximum line length is " x }''
  456.      This program prints the maximum line length of FILE.  The input is
  457.      piped through the `expand' program to change tabs into spaces, so
  458.      the widths compared are actually the right-margin columns.
  459. `awk 'BEGIN { FS = ":" }'
  460. `     { print $1 | "sort" }' /etc/passwd'
  461.      This program prints a sorted list of the login names of all users.
  462. `awk '{ nlines++ }'
  463. `     END { print nlines }''
  464.      This programs counts lines in a file.
  465. `awk 'END { print NR }''
  466.      This program also counts lines in a file, but lets `awk' do the
  467.      work.
  468. `awk '{ print NR, $0 }''
  469.      This program adds line numbers to all its input files, similar to
  470.      `cat -n'.
  471. File: gawk.info,  Node: Patterns,  Next: Actions,  Prev: One-liners,  Up: Top
  472. Patterns
  473. ********
  474.    Patterns in `awk' control the execution of rules: a rule is executed
  475. when its pattern matches the current input record.  This chapter tells
  476. all about how to write patterns.
  477. * Menu:
  478. * Kinds of Patterns::           A list of all kinds of patterns.
  479.                                 The following subsections describe
  480.                                 them in detail.
  481. * Regexp::                      Regular expressions such as `/foo/'.
  482. * Comparison Patterns::         Comparison expressions such as `$1 > 10'.
  483. * Boolean Patterns::            Combining comparison expressions.
  484. * Expression Patterns::         Any expression can be used as a pattern.
  485. * Ranges::                      Pairs of patterns specify record ranges.
  486. * BEGIN/END::                   Specifying initialization and cleanup rules.
  487. * Empty::                       The empty pattern, which matches every record.
  488. File: gawk.info,  Node: Kinds of Patterns,  Next: Regexp,  Prev: Patterns,  Up: Patterns
  489. Kinds of Patterns
  490. =================
  491.    Here is a summary of the types of patterns supported in `awk'.
  492. `/REGULAR EXPRESSION/'
  493.      A regular expression as a pattern.  It matches when the text of the
  494.      input record fits the regular expression. (*Note Regular
  495.      Expressions as Patterns: Regexp.)
  496. `EXPRESSION'
  497.      A single expression.  It matches when its value, converted to a
  498.      number, is nonzero (if a number) or nonnull (if a string). (*Note
  499.      Expressions as Patterns: Expression Patterns.)
  500. `PAT1, PAT2'
  501.      A pair of patterns separated by a comma, specifying a range of
  502.      records. (*Note Specifying Record Ranges with Patterns: Ranges.)
  503. `BEGIN'
  504. `END'
  505.      Special patterns to supply start-up or clean-up information to
  506.      `awk'.  (*Note `BEGIN' and `END' Special Patterns: BEGIN/END.)
  507. `NULL'
  508.      The empty pattern matches every input record. (*Note The Empty
  509.      Pattern: Empty.)
  510. File: gawk.info,  Node: Regexp,  Next: Comparison Patterns,  Prev: Kinds of Patterns,  Up: Patterns
  511. Regular Expressions as Patterns
  512. ===============================
  513.    A "regular expression", or "regexp", is a way of describing a class
  514. of strings.  A regular expression enclosed in slashes (`/') is an `awk'
  515. pattern that matches every input record whose text belongs to that
  516. class.
  517.    The simplest regular expression is a sequence of letters, numbers, or
  518. both.  Such a regexp matches any string that contains that sequence.
  519. Thus, the regexp `foo' matches any string containing `foo'. Therefore,
  520. the pattern `/foo/' matches any input record containing `foo'.  Other
  521. kinds of regexps let you specify more complicated classes of strings.
  522. * Menu:
  523. * Regexp Usage::                How to Use Regular Expressions
  524. * Regexp Operators::            Regular Expression Operators
  525. * Case-sensitivity::            How to do case-insensitive matching.
  526. File: gawk.info,  Node: Regexp Usage,  Next: Regexp Operators,  Prev: Regexp,  Up: Regexp
  527. How to Use Regular Expressions
  528. ------------------------------
  529.    A regular expression can be used as a pattern by enclosing it in
  530. slashes.  Then the regular expression is matched against the entire
  531. text of each record.  (Normally, it only needs to match some part of
  532. the text in order to succeed.)  For example, this prints the second
  533. field of each record that contains `foo' anywhere:
  534.      awk '/foo/ { print $2 }' BBS-list
  535.    Regular expressions can also be used in comparison expressions.  Then
  536. you can specify the string to match against; it need not be the entire
  537. current input record.  These comparison expressions can be used as
  538. patterns or in `if', `while', `for', and `do' statements.
  539. `EXP ~ /REGEXP/'
  540.      This is true if the expression EXP (taken as a character string)
  541.      is matched by REGEXP.  The following example matches, or selects,
  542.      all input records with the upper-case letter `J' somewhere in the
  543.      first field:
  544.           awk '$1 ~ /J/' inventory-shipped
  545.      So does this:
  546.           awk '{ if ($1 ~ /J/) print }' inventory-shipped
  547. `EXP !~ /REGEXP/'
  548.      This is true if the expression EXP (taken as a character string)
  549.      is *not* matched by REGEXP.  The following example matches, or
  550.      selects, all input records whose first field *does not* contain
  551.      the upper-case letter `J':
  552.           awk '$1 !~ /J/' inventory-shipped
  553.    The right hand side of a `~' or `!~' operator need not be a constant
  554. regexp (i.e., a string of characters between slashes).  It may be any
  555. expression.  The expression is evaluated, and converted if necessary to
  556. a string; the contents of the string are used as the regexp.  A regexp
  557. that is computed in this way is called a "dynamic regexp".  For example:
  558.      identifier_regexp = "[A-Za-z_][A-Za-z_0-9]+"
  559.      $0 ~ identifier_regexp
  560. sets `identifier_regexp' to a regexp that describes `awk' variable
  561. names, and tests if the input record matches this regexp.
  562. File: gawk.info,  Node: Regexp Operators,  Next: Case-sensitivity,  Prev: Regexp Usage,  Up: Regexp
  563. Regular Expression Operators
  564. ----------------------------
  565.    You can combine regular expressions with the following characters,
  566. called "regular expression operators", or "metacharacters", to increase
  567. the power and versatility of regular expressions.
  568.    Here is a table of metacharacters.  All characters not listed in the
  569. table stand for themselves.
  570.      This matches the beginning of the string or the beginning of a line
  571.      within the string.  For example:
  572.           ^@chapter
  573.      matches the `@chapter' at the beginning of a string, and can be
  574.      used to identify chapter beginnings in Texinfo source files.
  575.      This is similar to `^', but it matches only at the end of a string
  576.      or the end of a line within the string.  For example:
  577.           p$
  578.      matches a record that ends with a `p'.
  579.      This matches any single character except a newline.  For example:
  580.           .P
  581.      matches any single character followed by a `P' in a string.  Using
  582.      concatenation we can make regular expressions like `U.A', which
  583.      matches any three-character sequence that begins with `U' and ends
  584.      with `A'.
  585. `[...]'
  586.      This is called a "character set".  It matches any one of the
  587.      characters that are enclosed in the square brackets.  For example:
  588.           [MVX]
  589.      matches any one of the characters `M', `V', or `X' in a string.
  590.      Ranges of characters are indicated by using a hyphen between the
  591.      beginning and ending characters, and enclosing the whole thing in
  592.      brackets.  For example:
  593.           [0-9]
  594.      matches any digit.
  595.      To include the character `\', `]', `-' or `^' in a character set,
  596.      put a `\' in front of it.  For example:
  597.           [d\]]
  598.      matches either `d', or `]'.
  599.      This treatment of `\' is compatible with other `awk'
  600.      implementations, and is also mandated by the POSIX Command Language
  601.      and Utilities standard.  The regular expressions in `awk' are a
  602.      superset of the POSIX specification for Extended Regular
  603.      Expressions (EREs). POSIX EREs are based on the regular
  604.      expressions accepted by the traditional `egrep' utility.
  605.      In `egrep' syntax, backslash is not syntactically special within
  606.      square brackets.  This means that special tricks have to be used to
  607.      represent the characters `]', `-' and `^' as members of a
  608.      character set.
  609.      In `egrep' syntax, to match `-', write it as `---', which is a
  610.      range containing only `-'.  You may also give `-' as the first or
  611.      last character in the set.  To match `^', put it anywhere except
  612.      as the first character of a set.  To match a `]', make it the
  613.      first character in the set.  For example:
  614.           []d^]
  615.      matches either `]', `d' or `^'.
  616. `[^ ...]'
  617.      This is a "complemented character set".  The first character after
  618.      the `[' *must* be a `^'.  It matches any characters *except* those
  619.      in the square brackets (or newline).  For example:
  620.           [^0-9]
  621.      matches any character that is not a digit.
  622.      This is the "alternation operator" and it is used to specify
  623.      alternatives.  For example:
  624.           ^P|[0-9]
  625.      matches any string that matches either `^P' or `[0-9]'.  This
  626.      means it matches any string that contains a digit or starts with
  627.      `P'.
  628.      The alternation applies to the largest possible regexps on either
  629.      side.
  630. `(...)'
  631.      Parentheses are used for grouping in regular expressions as in
  632.      arithmetic.  They can be used to concatenate regular expressions
  633.      containing the alternation operator, `|'.
  634.      This symbol means that the preceding regular expression is to be
  635.      repeated as many times as possible to find a match.  For example:
  636.           ph*
  637.      applies the `*' symbol to the preceding `h' and looks for matches
  638.      to one `p' followed by any number of `h's.  This will also match
  639.      just `p' if no `h's are present.
  640.      The `*' repeats the *smallest* possible preceding expression. (Use
  641.      parentheses if you wish to repeat a larger expression.)  It finds
  642.      as many repetitions as possible.  For example:
  643.           awk '/\(c[ad][ad]*r x\)/ { print }' sample
  644.      prints every record in the input containing a string of the form
  645.      `(car x)', `(cdr x)', `(cadr x)', and so on.
  646.      This symbol is similar to `*', but the preceding expression must be
  647.      matched at least once.  This means that:
  648.           wh+y
  649.      would match `why' and `whhy' but not `wy', whereas `wh*y' would
  650.      match all three of these strings.  This is a simpler way of
  651.      writing the last `*' example:
  652.           awk '/\(c[ad]+r x\)/ { print }' sample
  653.      This symbol is similar to `*', but the preceding expression can be
  654.      matched once or not at all.  For example:
  655.           fe?d
  656.      will match `fed' and `fd', but nothing else.
  657.      This is used to suppress the special meaning of a character when
  658.      matching.  For example:
  659.           \$
  660.      matches the character `$'.
  661.      The escape sequences used for string constants (*note Constant
  662.      Expressions: Constants.) are valid in regular expressions as well;
  663.      they are also introduced by a `\'.
  664.    In regular expressions, the `*', `+', and `?' operators have the
  665. highest precedence, followed by concatenation, and finally by `|'. As
  666. in arithmetic, parentheses can change how operators are grouped.
  667. File: gawk.info,  Node: Case-sensitivity,  Prev: Regexp Operators,  Up: Regexp
  668. Case-sensitivity in Matching
  669. ----------------------------
  670.    Case is normally significant in regular expressions, both when
  671. matching ordinary characters (i.e., not metacharacters), and inside
  672. character sets.  Thus a `w' in a regular expression matches only a
  673. lower case `w' and not an upper case `W'.
  674.    The simplest way to do a case-independent match is to use a character
  675. set: `[Ww]'.  However, this can be cumbersome if you need to use it
  676. often; and it can make the regular expressions harder for humans to
  677. read.  There are two other alternatives that you might prefer.
  678.    One way to do a case-insensitive match at a particular point in the
  679. program is to convert the data to a single case, using the `tolower' or
  680. `toupper' built-in string functions (which we haven't discussed yet;
  681. *note Built-in Functions for String Manipulation: String Functions.).
  682. For example:
  683.      tolower($1) ~ /foo/  { ... }
  684. converts the first field to lower case before matching against it.
  685.    Another method is to set the variable `IGNORECASE' to a nonzero
  686. value (*note Built-in Variables::.).  When `IGNORECASE' is not zero,
  687. *all* regexp operations ignore case.  Changing the value of
  688. `IGNORECASE' dynamically controls the case sensitivity of your program
  689. as it runs.  Case is significant by default because `IGNORECASE' (like
  690. most variables) is initialized to zero.
  691.      x = "aB"
  692.      if (x ~ /ab/) ...   # this test will fail
  693.      
  694.      IGNORECASE = 1
  695.      if (x ~ /ab/) ...   # now it will succeed
  696.    In general, you cannot use `IGNORECASE' to make certain rules
  697. case-insensitive and other rules case-sensitive, because there is no way
  698. to set `IGNORECASE' just for the pattern of a particular rule.  To do
  699. this, you must use character sets or `tolower'.  However, one thing you
  700. can do only with `IGNORECASE' is turn case-sensitivity on or off
  701. dynamically for all the rules at once.
  702.    `IGNORECASE' can be set on the command line, or in a `BEGIN' rule. 
  703. Setting `IGNORECASE' from the command line is a way to make a program
  704. case-insensitive without having to edit it.
  705.    The value of `IGNORECASE' has no effect if `gawk' is in
  706. compatibility mode (*note Invoking `awk': Command Line.). Case is
  707. always significant in compatibility mode.
  708. File: gawk.info,  Node: Comparison Patterns,  Next: Boolean Patterns,  Prev: Regexp,  Up: Patterns
  709. Comparison Expressions as Patterns
  710. ==================================
  711.    "Comparison patterns" test relationships such as equality between
  712. two strings or numbers.  They are a special case of expression patterns
  713. (*note Expressions as Patterns: Expression Patterns.).  They are written
  714. with "relational operators", which are a superset of those in C. Here
  715. is a table of them:
  716. `X < Y'
  717.      True if X is less than Y.
  718. `X <= Y'
  719.      True if X is less than or equal to Y.
  720. `X > Y'
  721.      True if X is greater than Y.
  722. `X >= Y'
  723.      True if X is greater than or equal to Y.
  724. `X == Y'
  725.      True if X is equal to Y.
  726. `X != Y'
  727.      True if X is not equal to Y.
  728. `X ~ Y'
  729.      True if X matches the regular expression described by Y.
  730. `X !~ Y'
  731.      True if X does not match the regular expression described by Y.
  732.    The operands of a relational operator are compared as numbers if they
  733. are both numbers.  Otherwise they are converted to, and compared as,
  734. strings (*note Conversion of Strings and Numbers: Conversion., for the
  735. detailed rules).  Strings are compared by comparing the first character
  736. of each, then the second character of each, and so on, until there is a
  737. difference.  If the two strings are equal until the shorter one runs
  738. out, the shorter one is considered to be less than the longer one. 
  739. Thus, `"10"' is less than `"9"', and `"abc"' is less than `"abcd"'.
  740.    The left operand of the `~' and `!~' operators is a string. The
  741. right operand is either a constant regular expression enclosed in
  742. slashes (`/REGEXP/'), or any expression, whose string value is used as
  743. a dynamic regular expression (*note How to Use Regular Expressions:
  744. Regexp Usage.).
  745.    The following example prints the second field of each input record
  746. whose first field is precisely `foo'.
  747.      awk '$1 == "foo" { print $2 }' BBS-list
  748. Contrast this with the following regular expression match, which would
  749. accept any record with a first field that contains `foo':
  750.      awk '$1 ~ "foo" { print $2 }' BBS-list
  751. or, equivalently, this one:
  752.      awk '$1 ~ /foo/ { print $2 }' BBS-list
  753. File: gawk.info,  Node: Boolean Patterns,  Next: Expression Patterns,  Prev: Comparison Patterns,  Up: Patterns
  754. Boolean Operators and Patterns
  755. ==============================
  756.    A "boolean pattern" is an expression which combines other patterns
  757. using the "boolean operators" "or" (`||'), "and" (`&&'), and "not"
  758. (`!').  Whether the boolean pattern matches an input record depends on
  759. whether its subpatterns match.
  760.    For example, the following command prints all records in the input
  761. file `BBS-list' that contain both `2400' and `foo'.
  762.      awk '/2400/ && /foo/' BBS-list
  763.    The following command prints all records in the input file
  764. `BBS-list' that contain *either* `2400' or `foo', or both.
  765.      awk '/2400/ || /foo/' BBS-list
  766.    The following command prints all records in the input file
  767. `BBS-list' that do *not* contain the string `foo'.
  768.      awk '! /foo/' BBS-list
  769.    Note that boolean patterns are a special case of expression patterns
  770. (*note Expressions as Patterns: Expression Patterns.); they are
  771. expressions that use the boolean operators. *Note Boolean Expressions:
  772. Boolean Ops, for complete information on the boolean operators.
  773.    The subpatterns of a boolean pattern can be constant regular
  774. expressions, comparisons, or any other `awk' expressions.  Range
  775. patterns are not expressions, so they cannot appear inside boolean
  776. patterns.  Likewise, the special patterns `BEGIN' and `END', which
  777. never match any input record, are not expressions and cannot appear
  778. inside boolean patterns.
  779. File: gawk.info,  Node: Expression Patterns,  Next: Ranges,  Prev: Boolean Patterns,  Up: Patterns
  780. Expressions as Patterns
  781. =======================
  782.    Any `awk' expression is also valid as an `awk' pattern. Then the
  783. pattern "matches" if the expression's value is nonzero (if a number) or
  784. nonnull (if a string).
  785.    The expression is reevaluated each time the rule is tested against a
  786. new input record.  If the expression uses fields such as `$1', the
  787. value depends directly on the new input record's text; otherwise, it
  788. depends only on what has happened so far in the execution of the `awk'
  789. program, but that may still be useful.
  790.    Comparison patterns are actually a special case of this.  For
  791. example, the expression `$5 == "foo"' has the value 1 when the value of
  792. `$5' equals `"foo"', and 0 otherwise; therefore, this expression as a
  793. pattern matches when the two values are equal.
  794.    Boolean patterns are also special cases of expression patterns.
  795.    A constant regexp as a pattern is also a special case of an
  796. expression pattern.  `/foo/' as an expression has the value 1 if `foo'
  797. appears in the current input record; thus, as a pattern, `/foo/'
  798. matches any record containing `foo'.
  799.    Other implementations of `awk' that are not yet POSIX compliant are
  800. less general than `gawk': they allow comparison expressions, and
  801. boolean combinations thereof (optionally with parentheses), but not
  802. necessarily other kinds of expressions.
  803. File: gawk.info,  Node: Ranges,  Next: BEGIN/END,  Prev: Expression Patterns,  Up: Patterns
  804. Specifying Record Ranges with Patterns
  805. ======================================
  806.    A "range pattern" is made of two patterns separated by a comma, of
  807. the form `BEGPAT, ENDPAT'.  It matches ranges of consecutive input
  808. records.  The first pattern BEGPAT controls where the range begins, and
  809. the second one ENDPAT controls where it ends.  For example,
  810.      awk '$1 == "on", $1 == "off"'
  811. prints every record between `on'/`off' pairs, inclusive.
  812.    A range pattern starts out by matching BEGPAT against every input
  813. record; when a record matches BEGPAT, the range pattern becomes "turned
  814. on".  The range pattern matches this record.  As long as it stays
  815. turned on, it automatically matches every input record read.  It also
  816. matches ENDPAT against every input record; when that succeeds, the
  817. range pattern is turned off again for the following record.  Now it
  818. goes back to checking BEGPAT against each record.
  819.    The record that turns on the range pattern and the one that turns it
  820. off both match the range pattern.  If you don't want to operate on
  821. these records, you can write `if' statements in the rule's action to
  822. distinguish them.
  823.    It is possible for a pattern to be turned both on and off by the same
  824. record, if both conditions are satisfied by that record.  Then the
  825. action is executed for just that record.
  826. File: gawk.info,  Node: BEGIN/END,  Next: Empty,  Prev: Ranges,  Up: Patterns
  827. `BEGIN' and `END' Special Patterns
  828. ==================================
  829.    `BEGIN' and `END' are special patterns.  They are not used to match
  830. input records.  Rather, they are used for supplying start-up or
  831. clean-up information to your `awk' script.  A `BEGIN' rule is executed,
  832. once, before the first input record has been read.  An `END' rule is
  833. executed, once, after all the input has been read.  For example:
  834.      awk 'BEGIN { print "Analysis of `foo'" }
  835.           /foo/ { ++foobar }
  836.           END   { print "`foo' appears " foobar " times." }' BBS-list
  837.    This program finds the number of records in the input file `BBS-list'
  838. that contain the string `foo'.  The `BEGIN' rule prints a title for the
  839. report.  There is no need to use the `BEGIN' rule to initialize the
  840. counter `foobar' to zero, as `awk' does this for us automatically
  841. (*note Variables::.).
  842.    The second rule increments the variable `foobar' every time a record
  843. containing the pattern `foo' is read.  The `END' rule prints the value
  844. of `foobar' at the end of the run.
  845.    The special patterns `BEGIN' and `END' cannot be used in ranges or
  846. with boolean operators (indeed, they cannot be used with any operators).
  847.    An `awk' program may have multiple `BEGIN' and/or `END' rules.  They
  848. are executed in the order they appear, all the `BEGIN' rules at
  849. start-up and all the `END' rules at termination.
  850.    Multiple `BEGIN' and `END' sections are useful for writing library
  851. functions, since each library can have its own `BEGIN' or `END' rule to
  852. do its own initialization and/or cleanup.  Note that the order in which
  853. library functions are named on the command line controls the order in
  854. which their `BEGIN' and `END' rules are executed.  Therefore you have
  855. to be careful to write such rules in library files so that the order in
  856. which they are executed doesn't matter. *Note Invoking `awk': Command
  857. Line, for more information on using library functions.
  858.    If an `awk' program only has a `BEGIN' rule, and no other rules,
  859. then the program exits after the `BEGIN' rule has been run. (Older
  860. versions of `awk' used to keep reading and ignoring input until end of
  861. file was seen.)  However, if an `END' rule exists as well, then the
  862. input will be read, even if there are no other rules in the program. 
  863. This is necessary in case the `END' rule checks the `NR' variable.
  864.    `BEGIN' and `END' rules must have actions; there is no default
  865. action for these rules since there is no current record when they run.
  866. File: gawk.info,  Node: Empty,  Prev: BEGIN/END,  Up: Patterns
  867. The Empty Pattern
  868. =================
  869.    An empty pattern is considered to match *every* input record.  For
  870. example, the program:
  871.      awk '{ print $1 }' BBS-list
  872. prints the first field of every record.
  873. File: gawk.info,  Node: Actions,  Next: Expressions,  Prev: Patterns,  Up: Top
  874. Overview of Actions
  875. *******************
  876.    An `awk' program or script consists of a series of rules and
  877. function definitions, interspersed.  (Functions are described later. 
  878. *Note User-defined Functions: User-defined.)
  879.    A rule contains a pattern and an action, either of which may be
  880. omitted.  The purpose of the "action" is to tell `awk' what to do once
  881. a match for the pattern is found.  Thus, the entire program looks
  882. somewhat like this:
  883.      [PATTERN] [{ ACTION }]
  884.      [PATTERN] [{ ACTION }]
  885.      ...
  886.      function NAME (ARGS) { ... }
  887.      ...
  888.    An action consists of one or more `awk' "statements", enclosed in
  889. curly braces (`{' and `}').  Each statement specifies one thing to be
  890. done.  The statements are separated by newlines or semicolons.
  891.    The curly braces around an action must be used even if the action
  892. contains only one statement, or even if it contains no statements at
  893. all.  However, if you omit the action entirely, omit the curly braces as
  894. well.  (An omitted action is equivalent to `{ print $0 }'.)
  895.    Here are the kinds of statements supported in `awk':
  896.    * Expressions, which can call functions or assign values to variables
  897.      (*note Expressions as Action Statements: Expressions.).  Executing
  898.      this kind of statement simply computes the value of the expression
  899.      and then ignores it.  This is useful when the expression has side
  900.      effects (*note Assignment Expressions: Assignment Ops.).
  901.    * Control statements, which specify the control flow of `awk'
  902.      programs.  The `awk' language gives you C-like constructs (`if',
  903.      `for', `while', and so on) as well as a few special ones (*note
  904.      Control Statements in Actions: Statements.).
  905.    * Compound statements, which consist of one or more statements
  906.      enclosed in curly braces.  A compound statement is used in order
  907.      to put several statements together in the body of an `if',
  908.      `while', `do' or `for' statement.
  909.    * Input control, using the `getline' command (*note Explicit Input
  910.      with `getline': Getline.), and the `next' statement (*note The
  911.      `next' Statement: Next Statement.).
  912.    * Output statements, `print' and `printf'. *Note Printing Output:
  913.      Printing.
  914.    * Deletion statements, for deleting array elements. *Note The
  915.      `delete' Statement: Delete.
  916.